<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { mStyles } from "@/utils/useStyles";
import { useStore } from "@/stores/user";
import API from "@/service/api/order";
import kf from "@/service/api/faq";
import { useCustomCountdown } from '@/hook/useCountDown';
import { requestToast } from "@/utils/requestToast";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { useFullPage } from "@/hook/useFullPage";

// UID
const mStore = useStore();
const mRoute = useRoute();
const mRouter = useRouter();
const mInfo = mRoute.query;


// 表单数据
const mSubmit = ref(true)
const mFormData = reactive<Record<string, any>>({
    game_id: 0,
    game_name: '',
    uid: Number(mStore.token.uid),
    role_id: '',
    role_name: "",
    server_name: '',
    remark_pic: [],
    remark_content: '',
    order_num: ''
});


//赋值对应的用户信息
Object.keys(mInfo).forEach(key => {
    if (key in mFormData) {
        mFormData[key] = mInfo[key];
    }
});

const clkDynamicsValidateForm = () => {
    let isValid = true;

    if (!mFormData.remark_content) {
        //showToast('问题描述不能为空');
        isValid = false;
    }

    return isValid;
};

//点亮提交信息按钮
watch(
    () => clkDynamicsValidateForm(),
    (newConfig) => {
        if (clkDynamicsValidateForm()) {
            mSubmit.value = false;
        } else {
            mSubmit.value = true;
        }
    },
    { deep: true }
);

//提交成功后
const mKfShow = ref(true);
const mPhoneMactionSheetRef = ref();
// 倒计时功能
const { startCountdown, remaining } = useCustomCountdown({
    onCompleted: () => {
        mKfShow.value = false;
    }
});

// 提交表单
const clkSubmitForm = async () => {
    if (clkDynamicsValidateForm()) {

        // 只提取 remark_pic 的 path 字段
        const remark_pic_paths = Array.isArray(mFormData.remark_pic)
            ? mFormData.remark_pic.map((img: any) => img.path)
            : [];


        //添加sys_前缀
        const baseFormData: Record<string, any> = {};
        Object.keys(mFormData).forEach(key => {
            if (key != 'order_num') {
                baseFormData[`sys_${key}`] = mFormData[key];
            }else{
                baseFormData[key] = mFormData[key];
            }
        });

        const submitData = {
            ...baseFormData,
            sys_remark_pic: remark_pic_paths
        };

        const { status } = await requestToast(submitData, API.orderRestart, "提交成功")
        if (status) {
            mKfShow.value = true;
            mPhoneMactionSheetRef.value.openDialog();
            startCountdown(10);
        }
    } else {
        console.log('表单数据:', mFormData);
    }
};

const { removeCachedView } = useDynamicKeepAlive()
//确定按钮点击
const clkBeforeClose = () => {
    //提交成功移除缓存
    removeCachedView(mRoute)
    //通知列表页刷新
    removeCachedView('', 'order')

    mPhoneMactionSheetRef.value.closeDialog()
    // 跳转到工单列表页面
    mRouter.push({
        path: '/order',
        query: {
            active: 'processing'
        }
    })
}

const { pageRef } = useFullPage({
    excludeFixedElements: ['.gr-button']
})

</script>

<template>
    <cNavbar iTitle="重新提交问题" :iFontColor="mStyles?.color2" :iBgColor="mStyles?.color10" leftArrow iFixed></cNavbar>
    <div class="gr-height" ref="pageRef">
        <div class="gr-solve">
            <cVanForm id="restart">
                <div class="dynamic-form">
                    <div class="gr-input">
                        <label class="form-label text-[30px] font-medium">
                            <span class="color-[#FF3A37]">*</span>
                            情况描述
                        </label>
                        <cVanfield iBgColor="#FFFFFF" type="textarea" placeholder="请准确描述您遇到的问题以及上传相关截图，以便为您提供更好帮助..."
                            class="m-t-[25px] m-b-[25px] text-[16px] font-normal" v-model="mFormData.remark_content"
                            clearable autosize maxlength="1000" show-word-limit></cVanfield>
                    </div>
                </div>
                <cUploadImg v-model="mFormData['remark_pic']" :max="3" :mStyles="mStyles"
                    class="m-t-[15px] bg-[white] rounded-[24px] p-[20px]" />
            </cVanForm>
        </div>
        <div class="gr-info m-t-[25px]">
            <h1 class="text-[30px] font-medium m-b-[32px]">请确认提交账号信息无误</h1>
            <cVanfield readonly name="picker" label="游戏名称：" v-model="mFormData.game_name" class="m-b-[15px]">
            </cVanfield>
            <cVanfield readonly name="picker" label="区服名称：" v-model="mFormData.server_name" class="m-b-[15px]">
            </cVanfield>
            <cVanfield readonly name="picker" label="角色名称：" v-model="mFormData.role_name" class="m-b-[15px]">
            </cVanfield>
        </div>
        <div class="gr-button">
            <cButton iLinearGradien class="w-[100%]" :iColor="mStyles?.color10" @click="clkSubmitForm" round
                :disabled="mSubmit">
                提交信息</cButton>
        </div>
        <cVanActionSheet ref="mPhoneMactionSheetRef" :close-on-click-overlay="false" :iClose="false" :iButton="true"
            iText="查看工单" @is-Confirm="clkBeforeClose">
            <h1 class="text-[28px] m-b-[35px]">你的问题工单已提交成功，请耐心等待短信通知！</h1>
            <a :href="kf.getKfUrl()" v-show="mKfShow" class="gr-kf">
                <van-image src="/kf.png" width="6.4vmin"></van-image>
                <span>联系在线客服 <span class="text-[#FF3A37]">{{ `${remaining}s` }}</span></span>
            </a>
        </cVanActionSheet>
    </div>
</template>

<style lang="scss">
#restart .uploaded-images {
    grid-template-columns: repeat(auto-fill, minmax(19.2vmin, 1fr));
    gap: 2.5vmin;
}

#restart .image-item .delete-icon {
    right: -10px;
}
</style>

<style lang="scss" scoped>
:deep(.van-field__clear) {
    bottom: 0;
    right: 0;
    position: absolute;
}

:deep(.van-cell) {
    padding: 0 0 0 10px;
    overflow: visible;
}

:deep(.van-cell__value) {
    font-size: 30px;
    color: #3D3D3D;
}

.gr-height {
    padding: 23px 23px 170px 23px;
    background: #F6F6F6;
}

.gr-input {
    border-radius: 24px;
    padding: 30px 20px 30px 20px;
    margin-bottom: 20px;
    background: #FFFFFF;
    position: relative;

    :deep(.van-field__word-limit) {
        font-size: 24px;
        color: rgba(61, 61, 61, 0.6);
        position: absolute;
        top: -70px;
        right: 0;
        z-index: 99;
    }
}

.gr-info {
    padding: 25px 20px 20px 20px;
    background: #FFFFFF;
    border-radius: 24px;

    :deep(.van-field__label) {
        color: rgba(61, 61, 61, 0.6);
        font-size: 30px;
        width: 150px;
        margin-right: 0;
    }

    :deep(.van-field__value) {
        font-size: 30px;
    }

    :deep(.van-field__control) {
        color: rgba(61, 61, 61, 0.6);
    }

    :deep(.van-cell:after) {
        border-bottom: 0;
    }
}

.gr-solve {
    margin: 10px;
    border-radius: 20px;

    h1 {
        background: #ff7d7b;
        padding: 20px;
        color: $color10;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        text-align: center;
        font-size: calc($fontSize + 5px);
    }
}


.gr-order-phone {
    :deep(.van-cell:after) {
        border: none;
    }

    .phone {
        padding-bottom: 0px;
    }
}

.gr-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: env(safe-area-inset-bottom);
    background: white;
    padding: 45px;
}

.gr-kf {
    color: #3D3D3D;
    display: inline-flex;
    align-items: center;
}
</style>